#!/usr/bin/env python
# -*- coding: utf-8  -*-

# This file is part of an old version of the Opuntia's lightweight ESTdb.
# This code is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Izaskun Mallona
# izaskun.mallona@gmail.com
#
#This searches for descriptors in a fasta file

from html import *
import sys, os, subprocess
from Bio import SeqIO
import re
import cgi

form = cgi.FieldStorage()
query = form.getvalue('query') 
query = " "+query+" "

#opening fasta file to search

handle = open("/usr/lib/cgi-bin/opuntia/annotated.fasta", "rU")

#parsing and extracting all the SeqRecords

records = list(SeqIO.parse(handle, "fasta"))
handle.close()

selected = []
output = 0

for i in range(len(records)):
    if re.search(query, records[i].description) is not None:
        selected.append(records[i])
        output=1
    
if output==1:
    searched=open("/tmp/searched.fasta","w")
    SeqIO.write(selected,searched,"fasta")
    searched.close()   
            
    htmlUp()
    htmlSearchUp()
    print '<p style="font-family: monospace">'
    handle = open("/tmp/searched.fasta", "r")
    for line in handle:
        print "%s <br />" %line
    handle.close()
    print "</p>" 
    htmlBottom()

else:
    htmlUp()
    htmlSearchUp()
    print "<p>The keyword you entered didn't match to any sequence descriptor.</p>"
    htmlBottom()

